package main

import (
	"DMSKafka/config"
	"fmt"
	"github.com/Shopify/sarama"
	"github.com/pkg/errors"
	"log"
)

var testmes = []string{"测试", "数据库", "Kafka", "Golang", "华为云"}

// 生产者
func main() {
	conf, err := config.GetConfig()
	if err != nil {
		log.Printf("%+v\n", err)
		return
	}
	config := sarama.NewConfig()
	// 发送完数据需要leader和follow都确认
	config.Producer.RequiredAcks = sarama.WaitForAll
	// 新选出一个partition
	config.Producer.Partitioner = sarama.NewRandomPartitioner
	// 成功交付的消息将返回
	config.Producer.Return.Successes = true

	// 连接kafka
	client, err := sarama.NewSyncProducer(conf.Host, config)
	if err != nil {
		log.Printf("%+v\n", errors.WithStack(err))
		return
	}
	defer client.Close()
	// 构造消息
	msg := &sarama.ProducerMessage{}
	msg.Topic = conf.Topic
	for _, mes := range testmes {
		msg.Value = sarama.StringEncoder(mes)
		//发送消息
		pid, offset, err := client.SendMessage(msg)
		if err != nil {
			log.Printf("%+v\n", errors.Wrap(err, "发送失败"))
			return
		}
		fmt.Printf("pid:%v offset:%v\n", pid, offset)
	}
}
